package com.ziven.common.widget.setting;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;

import com.ziven.common.widget.R;
import com.ziven.common.widget.value.BooleanValue;
import com.ziven.common.widget.value.Checked;
import com.ziven.common.widget.value.Enable;
import com.ziven.common.widget.value.SameEffect;
import com.ziven.common.widget.value.TakeEffect;
import com.ziven.common.widget.value.Value;
import com.ziven.common.widget.value.ViewValue;
import com.ziven.common.widget.value.Visibility;
import com.ziven.easygo.util.Carry;

/**
 * @author Ziven
 */
public class SwitchPreferenceItem extends BasePreferenceItem {

    public SwitchPreferenceItem() {}

    @Override
    public Value effect() {
        return TakeEffect.values(
                TakeEffect.values(
                        Visibility.visible(),
                        Checked.checked(getBoolean()),
                        Enable.enable(isEnable())
                ).accept(my -> my.viewId = R.id.sub_switch_button),
                SameEffect.values(ViewValue.views(
                        R.id.title,
                        R.id.sub_title_1,
                        R.id.sub_title_2))
                        .add(ViewValue.nullView())
                        .accept(my -> my.value = Enable.enable(isEnable()))
        );
    }

    private boolean isEnable() {
        BooleanValue value = BooleanValue.ofTrue();
        obtainRelatedBoolean((Carry<Boolean>) data -> {
            if(value.isTrue() && !data) {
                value.not();
            }
        });
        return value.isTrue();
    }

    @Override
    public boolean onItemClick(BasePreferenceItem data, int position, @NonNull View view) {
        if(view.isEnabled()) {
            boolean checked = !getBoolean();
            putBoolean(checked);
            SwitchCompat switchCompat = view.findViewById(R.id.sub_switch_button);
            switchCompat.setChecked(checked);
        }
        return true;
    }
}
